package org.budo.spring.mvc.view.jphp;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.spring.mvc.view.jphp.launcher.JphpLauncher;
import org.budo.spring.mvc.view.jphp.loader.JphpTemplateLoader;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.view.AbstractTemplateView;

/**
 * @author li
 * @see org.springframework.web.servlet.view.freemarker.FreeMarkerView
 */
public class JphpView extends AbstractTemplateView {
    private static final Logger log = Slf4j.getLogger();

    private JphpTemplateLoader templateLoader = null;

    @Override
    protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = this.getUrl();
        Resource templateResource = this.getTemplateLoader().loadTemplate(url);

        log.debug("renderMergedTemplateModel, url=" + url + ", templateResource=" + templateResource + ", request=" + request);

        JphpLauncher launcher = new JphpLauncher();
        launcher.setOutputStream(response.getOutputStream());
        launcher.run(templateResource, true, false);
    }

    public JphpTemplateLoader getTemplateLoader() {
        return templateLoader;
    }

    public void setTemplateLoader(JphpTemplateLoader templateLoader) {
        this.templateLoader = templateLoader;
    }

    @Override
    public String toString() {
        return this.getClass().getName() + "@" + Integer.toHexString(this.hashCode()) + ", " + super.toString();
    }
}